#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# web_data_collector.py
# 数据保存到web_info.json

import re
import subprocess
import json
from datetime import datetime
from typing import Dict


class WebDataCollector:
    def __init__(self):
        self.web_info = {
            "collection_time": datetime.now().isoformat(),
            "version": None,
            "modules": [],
            "os": None,
            "config_path": "/etc/httpd/conf/httpd.conf"
        }

    def collect_web_info(self) -> Dict:
        """收集web基础信息（标准化输出）"""
        try:
            # 1. 获取web版本
            self._get_web_version()

            # 2. 获取加载的模块
            self._get_loaded_modules()

            # 3. 获取操作系统信息
            self._get_os_info()

            return self.web_info

        except Exception as e:
            raise Exception(f"Error collecting web info: {str(e)}")

    def _get_web_version(self):
        """获取web版本号"""
        try:
            result = subprocess.run(
                ['httpd', '-v'],
                capture_output=True,
                text=True,
                check=True
            )
            version_output = result.stderr if result.stderr else result.stdout
            version_match = re.search(r'Apache/([\d.]+)', version_output)
            if version_match:
                self.web_info['version'] = version_match.group(1)
            else:
                raise ValueError("无法从 httpd -v 输出中提取版本号")
        except subprocess.CalledProcessError as e:
            raise Exception(f"执行 httpd -v 失败: {e.stderr}")

    def _get_loaded_modules(self):
        """获取已加载模块列表"""
        try:
            result = subprocess.run(
                ['httpd', '-M'],
                capture_output=True,
                text=True,
                check=True
            )
            modules_output = result.stdout + result.stderr

            modules = []
            capture_modules = False

            for line in modules_output.splitlines():
                line = line.strip()

                # 检测模块列表开始
                if line == "Loaded Modules:":
                    capture_modules = True
                    continue

                # 跳过非模块行
                if not capture_modules or not line:
                    continue

                # 跳过警告信息行（如 [Sun Aug 03...]）
                if line.startswith('['):
                    continue

                # 提取模块名（处理不同格式）
                module = line.split()[0]
                if module.endswith('_module'):
                    modules.append(module)

            self.web_info['modules'] = modules

        except subprocess.CalledProcessError as e:
            raise Exception(f"执行 httpd -M 失败: {e.stderr}")

    def _get_os_info(self):
        """获取操作系统信息（兼容CentOS/RedHat）"""
        try:
            # 尝试读取CentOS特定文件
            with open('/etc/centos-release', 'r') as f:
                self.web_info['os'] = f.read().strip()
        except FileNotFoundError:
            # 回退到通用Linux发行版检测
            self.web_info['os'] = subprocess.getoutput(
                "grep PRETTY_NAME /etc/os-release | cut -d'=' -f2 | tr -d '\"'"
            )

    def save_to_file(self, filename: str = 'web_info.json') -> str:
        """保存数据到JSON文件"""
        with open(filename, 'w') as f:
            json.dump(self.web_info, f, indent=2)
        return filename


if __name__ == "__main__":
    # 独立测试时的用法
    collector = WebDataCollector()
    try:
        data = collector.collect_web_info()
        print("采集到的Web信息:")
        print(json.dumps(data, indent=2))

        saved_path = collector.save_to_file()
        print(f"数据已保存到: {saved_path}")
    except Exception as e:
        print(f"采集失败: {str(e)}")